import json
import sys
import re
import os
from datetime import datetime
from PyQt6.QtCore import QTimer, Qt, QCoreApplication
from again.Welcome.new_project import Ui_NewProject
import picture.resources_rc
from PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog
from pathlib import Path

PROJECTS_FILE = 'projects.json'

def load_projects():
    if os.path.exists(PROJECTS_FILE):
        with open(PROJECTS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_projects(projects):
    with open(PROJECTS_FILE, 'w', encoding='utf-8') as f:
        json.dump(projects, f, indent=4, ensure_ascii=False)

class NewProject(QMainWindow, Ui_NewProject):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 获取当前用户主目录
        user_home = os.path.expanduser("~")
        # 构造新的默认路径
        new_project_path = os.path.join(user_home, "wisdom_store_workspace", "Local")
        new_data_path = os.path.join(user_home, "wisdom_store_workspace", "Local")
        # 创建指定路径的文件夹

        path = Path(new_project_path)  # 替换为你想要创建的文件夹路径
        path.mkdir(parents=True, exist_ok=True)
        # 设置新的默认路径
        _translate = QCoreApplication.translate
        self.lineEditProjectPath.setText(_translate("NewProject", new_project_path))
        self.lineEditDataPath.setText(_translate("NewProject", new_data_path))
        self.lineEditProjectName.editingFinished.connect(self.checkProjectName)
        self.pBtnSupportFormat.clicked.connect(self.showSupportedFormats)
        self.pBtnSelecProjectPath.clicked.connect(self.browseInputDirectory)
        self.pBtnSelectDataPath.clicked.connect(self.browseOutputFile)
        self.pBtnCreate.clicked.connect(self.createProject)
        # 隐藏窗体顶部
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)

        # 设置鼠标追踪
        self.setMouseTracking(True)

        # 设置拖动相关变量
        self.is_maximized = False
        self.initDrag()

        # 记录初始位置和大小
        self.initial_geometry = self.geometry()

        # 连接窗口控制按钮
        self.pBtnClose.clicked.connect(self.close)

    # 窗口顶部的逻辑关闭、拖拽
    def initDrag(self):
        # 设置鼠标跟踪判断扳机默认值
        self.moveDrag = False

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MouseButton.LeftButton:  # 检查左键是否按下
            if not self.moveDrag:
                # 记录拖动的起始位置
                self.moveDragPosition = event.globalPosition().toPoint() - self.pos()
                self.moveDrag = True

            # 移动窗口到新的位置
            self.move(event.globalPosition().toPoint() - self.moveDragPosition)
            event.accept()
        else:
            self.moveDrag = False

    def mouseReleaseEvent(self, event):
        self.moveDrag = False

    def toolButtonsUnderMouse(self):
        return self.pBtnClose.underMouse()


    # 主体方法
    def checkProjectName(self):
        project_name = self.lineEditProjectName.text().strip()
        if not project_name or not re.match(r'^[\w\-]+$', project_name):
            QMessageBox.warning(self, "无效的项目名称", "重新填写项目名称")
            self.lineEditProjectName.setFocus()
            return False
        return True
    def showSupportedFormats(self):
        QMessageBox.information(self, "支持格式", "本软件支持导入arff、xlsx、xls、csv格式")

    def browseInputDirectory(self):
        user_home = os.path.expanduser("~")  # 获取当前用户的主目录
        default_path = os.path.join(user_home, "wisdom_store_workspace", "Local")  # 构造指定路径
        directory = QFileDialog.getExistingDirectory(self, "选择项目目录", default_path, QFileDialog.Option.ShowDirsOnly)
        if directory:
            self.lineEditProjectPath.setText(directory)

    def browseOutputFile(self):
        file_dialog = QFileDialog(self)
        file_dialog.setNameFilters(["Excel files (*.xlsx *.xls)", "JSON files (*.json)"])
        file_dialog.setViewMode(QFileDialog.ViewMode.Detail)  # 设置视图模式:
        # 获取用户主目录并构造默认路径
        user_home = os.path.expanduser("~")  # 获取当前用户的主目录
        print(user_home)
        default_path = os.path.join(user_home, "wisdom_store_workspace", "Local")  # 构造指定路径
        file_dialog.setDirectory(default_path)  # 设置默认目录
        if file_dialog.exec():  # 显示文件对话框并等待用户选择文件。exec() 方法会显示对话框并阻塞代码执行，直到用户选择了文件或取消了对话框
            file_path = file_dialog.selectedFiles()[0]
            self.lineEditDataPath.setText(file_path)


    def validateFields(self):
        project_name = self.lineEditProjectName.text().strip()
        input_path = self.lineEditProjectPath.text().strip()
        output_path = self.lineEditDataPath.text().strip()
        if not project_name or not input_path or not output_path:
            QMessageBox.warning(self, "警告", "请检查项目名称、项目目录、导入数据地址不能为空")
            return False

        if not os.path.isdir(input_path):
            QMessageBox.warning(self, "警告", "项目目录必须是一个文件夹，请重新选择文件位置")
            return False

        if not os.path.exists(output_path) or not re.match(r'.*\.(xlsx|xls|json)$', output_path):
            QMessageBox.warning(self, "警告", "重新导入数据地址")
            return False

        project_dir = os.path.join(input_path, project_name)
        if os.path.exists(project_dir):
            QMessageBox.warning(self, "警告", "项目名称已存在，请重新填写项目名称")
            return False

        return True

    def createProject(self):
        if not self.validateFields():
            return

        project_name = self.lineEditProjectName.text().strip()
        input_path = self.lineEditProjectPath.text().strip()
        data_path = self.lineEditDataPath.text().strip()
        project_dir = os.path.join(input_path, project_name)
        created_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # print(project_dir)
        try:
            os.makedirs(project_dir)
        except OSError as e:
            QMessageBox.warning(self, "错误", f"无法创建项目目录：{e}")
            return


        # 新项目的数据字典
        new_project = {
            "name": project_name,
            "directory": project_dir,
            "data_path": data_path,
            "created_time": created_time,
            "last_opened_time": created_time
        }

        # 读取现有的项目列表
        projects = load_projects()

        # 追加新项目
        projects.append(new_project)

        # 保存更新后的项目列表
        save_projects(projects)

        QMessageBox.information(self, "成功", "项目创建成功")
        self.showLoadingAnimation()
    def showLoadingAnimation(self):
        loading_dialog = QMessageBox(self)
        loading_dialog.setWindowTitle("创建项目中")
        loading_dialog.setText("请等待，项目正在创建中...")
        loading_dialog.setStandardButtons(QMessageBox.StandardButton.NoButton)
        loading_dialog.setModal(True)
        loading_dialog.show()

        QTimer.singleShot(2000, loading_dialog.accept)  # 模拟加载时间

        loading_dialog.finished.connect(self.openProjectPage)

    def openProjectPage(self):
        QMessageBox.information(self, "项目页面", "项目页面已打开")
        self.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = NewProject()
    mainWindow.show()
    sys.exit(app.exec())